package com.aaa.project.zhreport.service.impl;

import cn.hutool.core.util.StrUtil;
import com.aaa.common.exception.ServiceException;
import com.aaa.common.utils.SecurityUtils;
import com.aaa.framework.security.LoginUser;
import com.aaa.project.file.service.ISysFileService;
import com.aaa.project.zhreport.domain.YwfxFileDownloadRecord;
import com.aaa.project.zhreport.mapper.YwfxFileDownloadRecordMapper;
import com.aaa.project.zhreport.service.YwfxFileDownloadRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

/**
 * @author baibin
 * @version 1.0
 * @date 2025/4/10 14:05
 * @description YwfxFileDownloadRecordServiceImpl
 */
@Service
public class YwfxFileDownloadRecordServiceImpl implements YwfxFileDownloadRecordService {

    private static final Logger logger = LoggerFactory.getLogger(YwfxFileDownloadRecordServiceImpl.class);

    @Resource
    private YwfxFileDownloadRecordMapper ywfxFileDownloadRecordMapper;
    @Resource
    private ISysFileService sysFileService;

    @Override
    public List<YwfxFileDownloadRecord> list(YwfxFileDownloadRecord query) {
        logger.info("list request:{}", query);
        // 获取当前登录人
        LoginUser loginUser = SecurityUtils.getLoginUser();
        query.setCreateBy(loginUser.getUser().getUserName());
        return ywfxFileDownloadRecordMapper.list(query);
    }

    @Override
    public void download(Long id, HttpServletResponse response) {
        logger.info("download request:{}", id);
        YwfxFileDownloadRecord vo = ywfxFileDownloadRecordMapper.findById(id);
        if (vo == null) {
            throw new ServiceException("数据不存在");
        }
        // 根据fileUrl下载文件
        if (StrUtil.isBlank(vo.getFileUrl())) {
            throw new ServiceException("文件 URL 为空");
        }

        // 下载文件并写入响应
        InputStream inputStream = null;
        try {
            // 根据 fileUrl 获取文件资源
            URL url = new URL(vo.getFileUrl());
            inputStream = url.openStream();
            // 设置响应头
            response.reset();
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + getFileName(vo.getFileUrl()) + "\"");
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setContentType("application/octet-stream; charset=UTF-8");
            // 将文件内容写入响应流
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                response.getOutputStream().write(buffer, 0, bytesRead);
            }
            response.getOutputStream().flush();
            // 更新下载次数
            ywfxFileDownloadRecordMapper.updateDownloadCount(id);
        } catch (Exception e) {
            logger.error("文件下载失败，错误信息：{}", e);
            throw new ServiceException("文件下载失败");
        }
    }

    @Override
    public void delete(Long id) {
        logger.info("delete request:{}", id);
        YwfxFileDownloadRecord vo = ywfxFileDownloadRecordMapper.findById(id);
        if (vo == null) {
            throw new ServiceException("数据不存在");
        }
        ywfxFileDownloadRecordMapper.deleteById(id);
        // 删除文件
        if (StrUtil.isBlank(vo.getFileUrl())) {
            return;
        }
        sysFileService.deleteFile(vo.getFileUrl());
    }

    /**
     * 从文件 URL 中提取文件名
     *
     * @param fileUrl 文件 URL
     * @return 文件名
     */
    private String getFileName(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            return "file";
        }
        int lastSlashIndex = fileUrl.lastIndexOf('/');
        if (lastSlashIndex != -1 && lastSlashIndex < fileUrl.length() - 1) {
            return fileUrl.substring(lastSlashIndex + 1);
        }
        return "file";
    }
}
